<template >
  <div>
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float:right; margin-right: 30px" type="success" @click="exportExcel">导出</el-button>

        <el-button style="float:right; margin-right: 15px" @click="uploadExcel()">上传</el-button>

        <el-button style="float:right; margin-right: 30px" type="primary" @click="getLidarList()">查询</el-button>
        <el-button style="float:right; margin-right: 15px" @click="handleResetSearch()">重置</el-button>
      </div>
      <!-- 文件上传窗口 -->
      <el-dialog v-model="uploadDialogVisible" title="上传文件" width="600px">
          <el-upload class="upload-demo" drag action="" :show-file-list="false" :before-upload="handleBeforeUpload"
            :on-change="handleFileChange">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">点击或拖拽文件(.xlsx)到此区域进行上传</div>
          </el-upload>
          <el-table :data="uploadedData" v-if="uploadedData.length">
            <el-table-column prop="站点名" label="站点名" />
            <el-table-column prop="时间" label="时间" />
            <el-table-column prop="臭氧浓度" label="臭氧浓度" width="200" />
            <el-table-column prop="消光系数" label="消光系数" />
            <el-table-column prop="边界层高" label="边界层高" />    
          </el-table>
          <template #footer>
            <el-button @click="uploadData">上传</el-button>
            <el-button @click="uploadDialogVisible = false">取 消</el-button>
          </template>
        </el-dialog>
      <div style="margin-top: 30px; ">
        <el-form style="display: flex; align-items: center;">
          <div style="margin-left: 20px;">
            <el-form-item label="站点名：">
              <el-input class="input-width" v-model="queryParams.param.stationName" placeholder="站点名" clearable></el-input>
            </el-form-item>
          </div>
          <div class="block">
            <span class="demonstration">选择时间段 ：</span>
            <el-date-picker
              v-model="value1"
              type="datetimerange"
              range-separator="To"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </div>
        </el-form>

      </div>
    </el-card>

    <el-table :data="lidarList" empty-text="正在加载" @selection-change="handleSelectionChange" :broder="true" >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="stationName" label="站点名" />
      <el-table-column prop="datetime" label="时间" />
      <el-table-column label="臭氧浓度" >
        <template v-slot="scope">
          <span>{{ truncate(scope.row.extino3) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="消光系数">
      <template v-slot="scope">
        <span>{{ truncate(scope.row.co3) }}</span>
      </template>
    </el-table-column>
      <el-table-column label="ChAPRR" >
        <template v-slot="scope">
          <span>{{ truncate(scope.row.chaprr) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="ChASNR" >
        <template v-slot="scope">
        <span>{{ truncate(scope.row.chasnr) }}</span>
      </template>
      </el-table-column>
      <el-table-column prop="pbl" label="边界层高" />
      <el-table-column label="操作" width="200px">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)" type="primary">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteItem(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div>
  <el-pagination
    :current-page="queryParams.pageNum"
    :page-size="queryParams.pageSize"
    :page-sizes="[15, 30, 45]"
    :small="false"
    :disabled="false"
    :background="true"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleNumChange"
  />
</div>
<el-dialog v-model="dialogFormVisible" :before-close="beforeClose" title="修改信息" width="800" >
  <el-form ref="formRef" :model="updateForm" :rules="rules">
    <el-form-item prop="extino3" label="臭氧浓度：">
      <el-input v-model="updateForm.extino3" />
    </el-form-item>
    <el-form-item prop="co3" label="消光系数：">
      <el-input v-model="updateForm.co3" />
    </el-form-item>
    <el-form-item prop="chaprr" label="ChAPRR：">
      <el-input v-model="updateForm.chaprr" />
    </el-form-item>
    <el-form-item prop="chasnr" label="ChASNR：">
      <el-input v-model="updateForm.chasnr" />
    </el-form-item>
    <el-form-item prop="pbl" label="边界层高：">
      <el-input v-model="updateForm.pbl" />
    </el-form-item>
  </el-form>
  <el-button type="primary" style="margin-left: 50%;" @click="confirm()">提交</el-button>
</el-dialog>
</template>

<script lang="ts" setup>
import { fetchLidarByPage,updateLidar,uploadLider } from "../../../api/lidarApi";
import { nextTick, ref, reactive, onMounted, VueElement, computed } from "vue";
import * as XLSX from "xlsx";

// const value1 = ref<[Date, Date]>([
//   new Date(),
//   new Date(),
// ])
const value1 = ref<[Date | null, Date | null]>([null, null]);

// 查询参数

const dateRange =ref([null, null]);
const isInvalidTimePeriod = computed(() =>{
  const [start, end] = dateRange.value;
  return start && end && new Date(start) > new Date(end);
});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  param: {
    stationName:"",
    earliestDatetime:"",
    latestDatetime:""
  }
});
const lidarList = ref([]); // 直接使用 ref 定义数组
let total = ref(0);

function getLidarList() {
  console.log("0000000");
  // console.log("111111",value1.value[0]?.toLocaleString());
  queryParams.param.earliestDatetime = value1.value[0]?.toLocaleString() || '';
  queryParams.param.latestDatetime = value1.value[1]?.toLocaleString() || '';
  console.log("query",queryParams);
  fetchLidarByPage(queryParams)
    .then(res => {
      console.log('resdata',res)
      console.log("res.data.result.records",res.data.result);

      // 确保从 res 中提取数组
      lidarList.value = res.data.result.records; // 如果 res 是数组
      // 或者根据实际情况调整，如：towersList.value = res.data;
      total.value = res.data.result.total;
      console.log('queryParams.value',queryParams.param)
    })
    .catch(error => {
      console.error("Error fetching towers list:", error);
    });
}

function truncate(text) {
      // 判断字符串长度，如果超过10个字符，则截断并添加省略号
      return text.length > 10 ? text.slice(0, 10) + '...' : text;
}

const dialogFormVisible = ref(false);
const updateForm = ref({
  extino3: "",
  co3: "",
  chaprr: "",
  chasnr: "",
  pbl: "",
  
});
const handleEdit = (rowData = {}) => {
  dialogFormVisible.value = true;
  console.log("rowData", rowData);
  //弹窗打开form 声称是异步的
  nextTick(() => {
    //如果是编辑
    if (rowData) {
      Object.assign(updateForm.value, rowData);
      // updateForm.value = rowData
      console.log("这里是获取编辑数据", rowData);
    }
  });
};

const confirm = async () => {
  console.log("更新内容", updateForm);
  console.log("更新内容", updateForm.value);
  //把updateForm.value给列表的第一列
  let res = await updateLidar(updateForm.value);
  if (res.code == 20000) {
      ElMessage({
        message: "修改成功",
        type: "success",
        duration: 1000
      });
    getLidarList();
  } else {
    ElMessage({
      message: "修改失败",
      type: "error",
      duration: 1000
    });
  }
  dialogFormVisible.value = false;
};
//重置事件
const handleResetSearch = async () => {
  queryParams.param.stationName='',
  queryParams.param.earliestDatetime='',
  queryParams.param.latestDatetime='',
  value1.value = [null, null];
  getLidarList();
}

const handleSizeChange = val => {
  queryParams.pageSize = val;
  getLidarList();
};

const handleNumChange = val => {
  queryParams.pageNum = val;
  getLidarList();
};


//删除事件

const deleteItem = async (row) => {
  try {
    await ElMessageBox.confirm('是否要删除该商品信息', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await delete(row.id);
    ElMessage({
      message: '删除成功',
      type: 'success',
      duration: 1000
    });
    handleSearch();
  } catch (error) {
    // Handle cancel or error
  }
};

onMounted(() => {
  getLidarList();
});

//上传文件
const fieldMapping = {
  "站点名":"stationName",
  "时间":"datetime",
  "消光系数：":"co3" ,
  "ChAPRR":"chaprr" ,
  "ChASNR":"chasnr",
  "边界层高":"pbl",
}
const uploadedData = ref([])
const uploadDialogVisible = ref(false)
const convertedData = ref([])

function uploadExcel() {
  uploadDialogVisible.value = true;
}

const handleFileChange = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: 'array' });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet);

    // 在读取数据后，处理'监测时间'列并将其转换为UTC时间
    jsonData.forEach((row) => {
      if (row['监测时间']) {
        // 假设 '监测时间' 是字符串或者日期格式
        const localTime = new Date(row['监测时间']);
        
        // 获取年月日、小时、分钟和秒
        const year = localTime.getFullYear();
        const month = String(localTime.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，+1
        const day = String(localTime.getDate()).padStart(2, '0');
        const hours = String(localTime.getHours()).padStart(2, '0');
        const minutes = String(localTime.getMinutes()).padStart(2, '0');
        const seconds = String(localTime.getSeconds()).padStart(2, '0');
        
        // 将日期时间拼接成 'yyyy-mm-dd hh:mm:ss' 格式
        const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        
        // 将转换后的时间替换原来的时间
        row['监测时间'] = formattedTime;
      }
    })

    uploadedData.value = jsonData; // 将读取的数据保存到 uploadedData
  };

  reader.readAsArrayBuffer(file.raw);
};

const uploadData = async () => {
  let convertedData = convertFields(uploadedData)
  // 遍历 convertedData 数组，并将每个元素的 id 设置为 null
  convertedData.forEach(item => {
    item.id = 0;
  });
  console.log("convertedData",convertedData);
  uploadLider(convertedData)
    .then(response => {
      console.log('上传成功', response);
      uploadedData.value = []; // 清空上传数据
      uploadDialogVisible.value = false; // 关闭弹窗
      ElMessage({
          message: "修改成功",
          type: "success",
          duration: 1000
        });
      // 可以根据需要进一步处理响应
    })
    .catch(error => {
      console.error('上传失败', error);
      ElMessage({
        message: "修改失败",
        type: "error",
        duration: 1000
      });
      // 你可以通过 error.response 获取详细的失败信息（比如 status 或 message）
      if (error.response) {
        // 请求已发出，服务器响应了状态码，且响应体
        console.error('服务器返回错误:', error.response.data);
      } else if (error.request) {
        // 请求已发出，但没有收到响应
        console.error('没有收到响应:', error.request);
      } else {
        // 发生了一些其他错误
        console.error('请求错误:', error.message);
      }
    });
};

const convertFields = (data) => {
  console.log("datadatadatadata",data.value);
  return data.value.map(row => {
    let convertedRow = {};
    Object.keys(row).forEach(key => {
      const englishKey = fieldMapping[key];
      if (englishKey) {
        // 如果是检测时间字段（detectionTime），则转换为国际时间格式
        // if (englishKey === 'detectionTime') {
        //   convertedRow[englishKey] = formatTimestamp(row[key]); // 格式化时间戳
        // } else {
          convertedRow[englishKey] = row[key];
        // }
      }
    });
    return convertedRow;
  });
};

const formatTimestamp = (timestamp) => {
  const date = new Date(timestamp); // 将时间戳转换为 Date 对象
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const convertedDataWithFormattedTime = convertedData.value.map(row => {
  console.log("11111111",convertedData.value)
  return {
    ...row,
    detectionTime: formatTimestamp(row.detectionTime)
  };
});
//选中数据
const selectedItems = ref([]); // 直接使用 ref 定义数组

function handleSelectionChange(selected) {
      selectedItems.value = selected; // 更新选中的项
      // console.log(selectedItems.value);
}
//下载文件
function exportExcel() {
  // 准备数据
  const data = selectedItems.value;

  // 检查数据是否为空
  if (data.length === 0) {
    console.error("没有可导出的数据");
        ElMessage({
        message: "没有可导出的数据",
        type: "error",
        duration: 1000
      });
    return;
  }

  // 创建工作簿
  const worksheet = XLSX.utils.json_to_sheet(data);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

  // 导出
  XLSX.writeFile(workbook, "data.xlsx");
}
</script>

<style lang="less">

.truncate-text {
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 隐藏溢出的内容 */
  text-overflow: ellipsis; /* 省略号表示溢出的内容 */
  width: 100px; /* 设置宽度以触发省略号 */
}

// 选择器样式
.block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
 // display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>